package com.h117121.fashionshop.core.dom;

import java.util.ArrayList;
import java.util.List;

public class Cart {
	private List<ProductInCart> items;
	private long total;
	private int numItems;

	public Cart() {
		setItems(new ArrayList<ProductInCart>());
	}

	public void add(Product product) {
		for (ProductInCart item : items) {
			if (item.getProduct().getId() == product.getId()) {
				item.setQuantity(item.getQuantity() + 1);
				return;
			}
		}

		items.add(new ProductInCart(product));
	}

	public void add(Product product, int quantity) {
		for (ProductInCart item : items) {
			if (item.getProduct().getId() == product.getId()) {
				item.setQuantity(item.getQuantity() + quantity);
				return;
			}
		}

		items.add(new ProductInCart(product, quantity));
	}

	public boolean update(long productId, int quantity) {
		for (ProductInCart item : items) {
			if (item.getProduct().getId() == productId) {
				item.setQuantity(quantity);
				return true;
			}
		}
		return false;
	}

	public void remove(long productId) {
		for (ProductInCart item : items) {
			if (item.getProduct().getId() == productId) {
				items.remove(item);
				return;
			}
		}
	}

	public boolean remove(long[] productIds) {
		ArrayList<ProductInCart> list = new ArrayList<ProductInCart>();
		for (ProductInCart item : items) {
			for (long id : productIds) {
				if (item.getProduct().getId() == id) {
					list.add(item);
					break;
				}
			}
		}
		return items.removeAll(list);
	}

	public List<ProductInCart> getItems() {
		return items;
	}

	public void setItems(List<ProductInCart> items) {
		this.items = items;
	}

	public long getTotal() {
		long temp = 0;
		for (ProductInCart item : items) {
			temp += (item.getProduct().getPrice() * item.getQuantity());
		}
		total = temp;
		return total;
	}

	public void setTotal(long total) {
		this.total = total;
	}

	public int getNumItems() {
		int temp = 0;
		for (ProductInCart item : items) {
			temp += item.getQuantity();
		}
		numItems = temp;
		return numItems;
	}

	public void setNumItems(int numItems) {
		this.numItems = numItems;
	}

}
